/*
 * Copyright (c) 2018. czmc All Rights Reserved.
 * Author: czmc
 * Email: zxc6355533@163.com
 * Encoding: UTF-8
 */

package top.stime21.myneighbours.api;

import com.orhanobut.logger.Logger;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;

import org.json.JSONObject;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import top.stime21.myneighbours.data.dto.StringResult;


public class UploadManager {

    private UploadManager() {
    }

    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final UploadManager INSTANCE = new UploadManager();
    }

    //获取单例
    public static UploadManager ins() {
        return SingletonHolder.INSTANCE;
    }

    public Observable<String> upload(final File file, final String key) {
        return Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(final ObservableEmitter<String> emitter) throws Exception {
                ApiManager.Companion.ins().getDataApi().getTokenQiniu()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<StringResult>() {
                                       @Override
                                       public void accept(StringResult s) throws Exception {

                                           if (s.isSuccess()) {
                                               Configuration config = new Configuration.Builder()
                                                       .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认256K
                                                       .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认512K
                                                       .connectTimeout(10) // 链接超时。默认10秒
                                                       .responseTimeout(60) // 服务器响应超时。默认60秒
                                                       .zone(Zone.zone0) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。默认 Zone.zone0
                                                       .build();

                                               com.qiniu.android.storage.UploadManager uploadManager = new com.qiniu.android.storage.UploadManager(config);
                                               String token = s.getData();
                                               Logger.i("qntoken=" + token);
                                               if (file == null)
                                                   emitter.onError(new RuntimeException("file is null!"));
                                               uploadManager.put(file, key, token,
                                                       new UpCompletionHandler() {
                                                           @Override
                                                           public void complete(String key, ResponseInfo info, JSONObject res) {
                                                               //res包含hash、key等信息，具体字段取决于上传策略的设置。
                                                               Logger.i(key + ",\r\n " + info + ",\r\n " + res);
                                                               if (info.isOK()) {
                                                                   emitter.onNext(key);
                                                               }
                                                           }
                                                       }, null);
                                           }
                                       }
                                   }, new Consumer<Throwable>() {
                                       @Override
                                       public void accept(Throwable throwable) throws Exception {
                                           emitter.onError(throwable);
                                       }
                                   }
                        );
            }
        });

    }
}